#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "tp3.h"

  void  AdicionaSK(char *buffer, char *titulo, PK *listaSK, int *nSK, FILE *file, FILE *avail, int tm)
  {
    int navail, b, NRR=0, NRRwrt;
    char test[200],titulowrt[200];
    PK *found;
    if((*nSK)>0){
      found=BSearch(listaSK,buffer,0,(*nSK)-1);
    }
    else{
      found=NULL;
    }
    if(found==NULL){
      fread(&navail,1,4,avail);
      if(navail==-1){
        while(fgets(test,tm,file)!=NULL){
          NRR++;
          fseek(file,NRR*(tm+4),0);
        }
        for(b=0;b<tm;b++){
          titulowrt[b]=titulo[b];
        }
        fwrite(titulowrt,1,tm,file);
        NRRwrt=-1;
        fwrite(&NRRwrt,1,4,file);
      }
      else{
        fseek(file,(navail*(tm+4))+1,0);
        NRR=navail;
        fread(&navail,1,4,file);
        fseek(avail,0,0);
        fwrite(&navail,1,4,avail);
        fseek(file,NRR*(tm+4),0);
        for(b=0;b<tm;b++){
         titulowrt[b]=titulo[b];
        }
	fwrite(titulowrt,1,tm,file);
        NRRwrt=-1;
        fwrite(&NRRwrt,1,4,file);
      }
      if((*nSK)%20==0){
        listaSK=(PK*)realloc(listaSK,((*nSK)+20)*sizeof(PK));
      }
      for(b=0;b<200;b++){
        listaSK[*nSK].titulo[b]=buffer[b];
      }
      listaSK[*nSK].NRR=NRR;
      (*nSK)++;
    }
    else{
      fread(&navail,1,4,avail);
      if(navail==-1){
        while(fgets(test,tm,file)!=NULL){
          NRR++;
          fseek(file,NRR*(tm+4),0);
        }
        for(b=0;b<tm;b++){
          titulowrt[b]=titulo[b];
        }
        fwrite(titulowrt,1,tm,file);
        NRRwrt=found->NRR;
        fwrite(&NRRwrt,1,4,file);
      }
      else{
        fseek(file,(navail*(tm+4))+1,0);
        NRR=navail;
        fread(&navail,1,4,file);
        fseek(avail,0,0);
        fwrite(&navail,1,4,avail);
        fseek(file,NRR*(tm+4),0);
        for(b=0;b<tm;b++){
          titulowrt[b]=titulo[b];
        }
        fwrite(titulowrt,1,tm,file);
        NRRwrt=-1;
        fwrite(&NRRwrt,1,4,file);
      }
      found->NRR=NRR;
    }
    NRR=0;
    Ordena(listaSK,0,(*nSK)-1);
  }
